import Vue from 'vue'
import axios from 'axios'

// create an axios instance
const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : 'http://pergo.weilang.top/api/v1'

const service = axios.create({
  baseURL: baseUrl,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['x-token'] = sessionStorage.getItem('token') ? sessionStorage.getItem('token') : ''
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error. res.status !== 200 

    if (res.code !== 200) {
      if (res.code === 500 || res.code === 400 || res.code === 403) {
        Vue.$vux.toast.text(res.msg, 'top')
        return res
      } else {
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
